package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhentao.mapper.ESArticleMapper;
import com.zhentao.model.article.pojo.ApArticle;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.pojo.SearchArticleVo;
import com.zhentao.service.ApArticleService;
import lombok.SneakyThrows;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Date 2024/6/6 10:25
 * @Author xdm
 **/
@Service
public class ApArticleServiceImpl implements ApArticleService {
    @Autowired
    private ESArticleMapper apArticleMapper;
    @Autowired
    private RestHighLevelClient client;


    @SneakyThrows
    @Override
    public ResponseResult esinit() {
        //1.把数据从数据库里面查询出来
        List<ApArticle> apArticleList = apArticleMapper.selectList(null);
        //2.把数据导入es
        BulkRequest bulkRequest = new BulkRequest("app_info_article");

        for (ApArticle apArticle : apArticleList) {

            SearchArticleVo searchArticleVo = new SearchArticleVo();
            BeanUtils.copyProperties(apArticle, searchArticleVo);

            IndexRequest indexRequest = new IndexRequest()
                    .id(searchArticleVo.getId() + "")
                    .source(JSON.toJSONString(searchArticleVo), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        client.bulk(bulkRequest, RequestOptions.DEFAULT);

        return ResponseResult.okResult("导入成功" + apArticleList.size());


    }
}